﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.CodeRush.Core;
using System.Windows.Forms;
using DevExpress.CodeRush.StructuralParser;
using System.Diagnostics;

namespace DX_SourceOutliner
{
    public class SourceTreeBuilder
    {
        private TreeNode BuildDocumentTree(TextDocument document)
        {
            TreeNode documentNode = new TreeNode { Tag = new SourceTreeNode { ElementName = document.Name } };            

            foreach (var item in document.FileNode.Nodes)
            {
                LanguageElement element = item as LanguageElement;

                if (element != null)
                {
                    documentNode = AddChildren(documentNode, element);
                }
            }

            return documentNode;
        }


        private TreeNode AddChildren(TreeNode parent, LanguageElement element)
        {
            foreach (LanguageElement childElement in element.Nodes)
            {
                TreeNode childElementNode = new TreeNode { Tag = new SourceTreeNode(childElement) };
                
                foreach (LanguageElement subElement in childElement.Nodes)
                {
                    TreeNode subElementNode = new TreeNode { Tag = new SourceTreeNode(subElement) };
                    
                    subElementNode = AddChildren(subElementNode, subElement);
                    childElementNode.Nodes.Add(subElementNode);
                }

                parent.Nodes.Add(childElementNode);
            }
            return parent;
        }


        public IEnumerable<TreeNode> BuildTree()
        {
            IList<TreeNode> results = new List<TreeNode>();

            var documents = CodeRush.Documents.AllTextDocuments;

            foreach (Document document in documents)
            {
                TextDocument workingDoc = document as TextDocument;
                TreeNode documentNode;
                if (workingDoc != null)
                {
                    documentNode = BuildDocumentTree(workingDoc);
                    results.Add(documentNode);
                }
            }

            return results;
        }
    }
}
